package cn.tradewin.pmp.services.download.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.services.Response;

import cn.tradewin.common.util.MimeSymbols;
import cn.tradewin.pmp.services.download.OutputStreamResponse;

public class PdfOutputStreamResponse implements OutputStreamResponse {

	private final String filename;
	private final Asset jasper;
	private final Map<String,Object> parameters; 
	private final JRDataSource jrDataSource;
	
	public PdfOutputStreamResponse(Asset jasper, Map<String, Object> parameters, JRDataSource jrDataSource, String filename) {
	   this.jasper = jasper;
	   this.parameters = parameters;
	   this.jrDataSource = jrDataSource;
	   this.filename = filename;
	}
	
	
	@Override
	public String getContentType() {
		return MimeSymbols.APPLICATION_PDF;
	}

	@Override
	public void writeToStream(OutputStream out) throws IOException {
		
		try {
			JasperRunManager.runReportToPdfStream(jasper.getResource().openStream(), out, this.parameters, this.jrDataSource);
		} catch (JRException e) {
			StringWriter stringWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(stringWriter);
			e.printStackTrace(printWriter);
			out.write(stringWriter.toString().getBytes());
		}
	}

	@Override
	public void prepareResponse(Response response) {
		try {
			String output = new File(filename).getName();
			// 如果不设定该header的值，就会直接在浏览器上显示的内容。
			response.setHeader("Content-Disposition", "attachment; filename=\""  + URLEncoder.encode(output, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}
